package com.meisupic.copyright.controller;

import static com.meisupic.copyright.common.AuthorizeRuleEnum.OfflineAuthorize;
import static com.meisupic.copyright.common.Constants.PUBLISH_STATUS_PUBLISHED;

import com.alibaba.fastjson.JSONObject;
import com.meisupic.copyright.domain.bo.ImageInfo;
import com.meisupic.copyright.domain.po.CopyRightWorks;
import com.meisupic.copyright.domain.query.WorksQuery;
import com.meisupic.copyright.domain.vo.CategroyVo;
import com.meisupic.copyright.domain.vo.CopyRightWorksResponseVo;
import com.meisupic.copyright.domain.vo.CopyRightWorksRowVo;
import com.meisupic.copyright.domain.vo.CopyRightWorksVo;
import com.meisupic.copyright.domain.vo.MessageVo;
import com.meisupic.copyright.exception.BizException;
import com.meisupic.copyright.service.ICopyRightWorksService;
import com.meisupic.copyright.service.IMessageService;
import com.meisupic.copyright.service.IOssService;
import com.meisupic.copyright.service.VipMemberService;
import com.meisupic.copyright.support.Message;
import com.meisupic.copyright.util.IpHelper;
import com.meisupic.copyright.util.StringUtil;
import com.meisupic.copyright.validategroups.Published;
import com.yuanbenlian.common.InvalidException;
import com.yuanbenlian.model.http.MetadataQueryResp;
import com.yuanbenlian.service.NodeProcessor;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * creation wuxun
 *
 * @version V1.0
 * @Description: 作品版权登记控制器
 * @date 2018/1/20 15:23
 */
@RestController
@RequestMapping("/copyright")
public class CopyRightWorksController extends BaseController {

  @Autowired
  Validator hibernateValidator;

  @Autowired
  ICopyRightWorksService copyRightWorksService;

  @Autowired
  IMessageService messageService;

  @Autowired
  IOssService ossService;

  @Autowired
  private Md5PasswordEncoder md5PasswordEncoder;

  @Autowired
  private VipMemberService vipMemberService;

  @Value("${yuanben.server.url}")
  private String ybServerUrl;


  @PostMapping("/save")
  public Message saveCopyrightWorks(@RequestBody @Validated CopyRightWorksVo copyRightWorksVo) {
    //TODO 判断作品类型值是否合法 发表日期大于创作日期
    if (PUBLISH_STATUS_PUBLISHED == copyRightWorksVo.getPublishStatus()) {
      Set<ConstraintViolation<CopyRightWorksVo>> resultSet = hibernateValidator
          .validate(copyRightWorksVo, Published.class);
      if (!resultSet.isEmpty()) {
        for (ConstraintViolation<CopyRightWorksVo> constraintViolation : resultSet) {
          throw new BizException(constraintViolation.getMessage());
        }
      }
      Date firstPublishDate = copyRightWorksVo.getFirstPublishDate();
      Date creativeDate = copyRightWorksVo.getCreationDate();
      if (firstPublishDate.before(creativeDate)) {
        throw new BizException("首次发表日期不能小于创作日期");
      }
    }
    if (OfflineAuthorize == copyRightWorksVo.getAuthorizeRule()) {
      //校验服务可用数量
      boolean available = vipMemberService
          .vipServiceIsAvailable(getUserId(), copyRightWorksVo.getImagesName().size());
      if (!available) {
        throw new BizException("VIP服务可用数量不足");
      }
    }
    Long userId = getUserId();
    List<CopyRightWorks> copyRightWorksList = copyRightWorksService
        .saveWorks(copyRightWorksVo, userId);

    return Message.success(copyRightWorksList);
  }

  /**
   * 拒绝时修改页面返回CopyRightWorksResponseVO
   */
  @GetMapping("/findWorksVoById")
  public Message<CopyRightWorksResponseVo> findWorksVoById(Long id) {

    CopyRightWorksResponseVo responseVO = copyRightWorksService
        .findCopyRightWorksResponseVOById(id, false);
    return Message.success(responseVO);
  }

  @GetMapping("/reEditWorksById")
  public Message<CopyRightWorksResponseVo> reEditWorksById(Long id) {

    CopyRightWorksResponseVo responseVO = copyRightWorksService
        .findCopyRightWorksResponseVOById(id, true);
    return Message.success(responseVO);
  }

  /**
   * 确认登记信息操作
   */
  @GetMapping("confirm")
  public Message confirm(Long id) {
    List<String> dnaList = copyRightWorksService.confirmWorksInfo(id);
    return Message.success(dnaList.size());
  }

  @GetMapping("getCategoryList")
  public List<CategroyVo> getCategoryList() {
    return copyRightWorksService.findCategoryVoList();
  }

  @GetMapping("commitWorks")
  public Message commitWorks(Long id) {
    List<String> dnaList = copyRightWorksService.confirmWorksInfo(id);
    return Message.success(dnaList);
  }

  /**
   * 分页获取作品数据
   */
  @PostMapping("getWorksPage")
  public Page<CopyRightWorksRowVo> getWorksPage(WorksQuery worksQuery,
      @PageableDefault(sort = {"createTime"}, direction = Direction.DESC) Pageable pageable) {
    worksQuery.setCreatorId(getUserId());
    Page<CopyRightWorksRowVo> worksRowVos = copyRightWorksService
        .findPageCopyRightWorkRowVO(worksQuery, pageable);
    return worksRowVos;
  }

  /**
   * 作品信息详情页查找单个作品信息
   */
  @GetMapping("findSingleWorksVo")
  public CopyRightWorksRowVo findSingleWorksVo(Long id) {
    CopyRightWorksRowVo worksRowVo = copyRightWorksService.findSingleWorksVo(id);
    return worksRowVo;
  }

  /**
   * 作品信息详情页查找单个作品信息
   */
  @GetMapping("findSingleWorksVoByGoodsId")
  public CopyRightWorksRowVo findSingleWorksVoByGoodsId(Long goodsId) {
    CopyRightWorksRowVo worksRowVo = copyRightWorksService.findSingleWorksVoByGoodsId(goodsId);
    return worksRowVo;
  }

  @GetMapping("deleteWorksById")
  public Message deleteWorksById(Long id) {
    copyRightWorksService.deleteWorks(id);
    return Message.success("删除成功");
  }

  @GetMapping("getUserIdAndSecret")
  public String getUserIdAndSecret() {
    Long userId = getUserId();
    String keyId = StringUtil.get32UUID().substring(0, 6);
    String secret = md5PasswordEncoder.encodePassword((keyId + userId), null);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("userId", userId);
    jsonObject.put("keyId", keyId);
    jsonObject.put("secret", secret);
    return jsonObject.toJSONString();
  }

  @GetMapping("getCommitedWorksNum")
  public String getCommitedWorksNum() {
    int commitedNum = copyRightWorksService.countCommitedWorks(getUserId());
    return String.valueOf(commitedNum);
  }

  @GetMapping("findLatestWorks")
  public List<CopyRightWorksRowVo> findLatestWorks() {
    return copyRightWorksService.findLatestWorks(getUserId());
  }

  @GetMapping("findLatestMessages")
  public List<MessageVo> findLatestMessages() {
    return messageService.findLastedMessage(getUserId());
  }

  @GetMapping("getImageInfo")
  public ImageInfo getImageInfo(String imageKey) {
    return ossService.getImageInfo(imageKey);
  }

  @GetMapping("getDnaDetail")
  public MetadataQueryResp getDnaDetail(String dna) {
    try {
      return NodeProcessor.QueryMetadata(ybServerUrl, dna);
    } catch (InvalidException e) {
      e.printStackTrace();
      throw new BizException("获取dna详情异常");
    }
  }

  @GetMapping("getGoodsSn")
  public String getGoodsSnByGoodsId(Long worksId) {
    return copyRightWorksService.getGoodsSn(worksId);
  }

  @PostMapping("isRepeatedWorksName")
  public boolean isRepeatedWorksName(Long id, String worksFullName) {
    return copyRightWorksService.isRepeatedWorksName(id, worksFullName);
  }

  @GetMapping("getIpAddress")
  public String getDefaultAddress() {
    return IpHelper.getIpAddr(request);
  }
}
